<template>
  <div>
    <Category :isShow="isShow" />
    <el-card style="margin: 10px 0">
      <div v-show="!isShow">
        <el-button
          type="primary"
          size="default"
          icon="Plus"
          :disabled="!CategoryStore.c3Id"
          @click="isShow = true"
          v-has="`btn.Attr.add`"
        >
          添加属性
        </el-button>
        <el-table
          border
          :data="AttrList"
          v-loading="loding"
          element-loading-text="加载中..."
        >
          <el-table-column
            label="序号"
            type="index"
            width="80"
            align="center"
            prop="id"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            width="120"
            prop="attrName"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #default="{ row }">
              <el-tag
                type="primary"
                v-for="item in row.attrValueList"
                :key="item.id"
              >
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                icon="Edit"
                @click="updateAttrValue(row)"
                v-has="`btn.Attr.update`"
              ></el-button>
              <el-popconfirm
                width="220"
                confirm-button-text="确认"
                cancel-button-text="取消"
                icon="InfoFilled"
                icon-color="#626AEF"
                :title="`确定要删除属性${row.attrName}?`"
                @confirm="attrDelete(row.id)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    size="small"
                    icon="Delete"
                    v-has="`btn.Attr.remove`"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 添加属性 -->
      <div v-show="isShow">
        <el-form :inline="true">
          <el-form-item label="属性名称" size="default">
            <el-input
              v-model.trim="attr.attrName"
              placeholder="请输入属性名称"
              size="default"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          :disabled="!attr.attrName"
          type="primary"
          size="default"
          @click="addValueList"
          icon="Plus"
          style="margin: 10px 5px"
        >
          添加属性值
        </el-button>
        <el-button type="primary" size="default" @click="isShow = false">
          取消
        </el-button>
        <el-table :data="attr.attrValueList" border>
          <el-table-column
            type="index"
            label="序号"
            width="55"
            align="center"
          />
          <el-table-column label="属性名">
            <template #default="{ row, $index }">
              <!-- //统一编码001将添加的组件的vc实例存储到一个数组给elinput加focus事件 -->
              <!-- :ref="(vc: any) => (inputArr[$index] = vc)" -->
              <el-input
                v-focus
                v-if="row.flag"
                @blur="mouseBlur(row, $index)"
                v-model.trim="row.valueName"
                placeholder="请输入属性值名称"
                size="default"
                clearable
              ></el-input>
              <!-- 用户点击div时把当前行的index传给方法用于input实例的focus -->
              <div v-else @click="editCon(row)">
                {{ row.valueName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ $index }">
              <el-button
                type="danger"
                size="small"
                icon="Delete"
                @click="attr.attrValueList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          :disabled="!attr.attrValueList.length"
          type="primary"
          size="default"
          @click="saveAttrList"
          style="margin: 10px 5px"
        >
          保存
        </el-button>
        <el-button size="default" @click="clearnAttr">清空</el-button>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup name="index">
//cate仓库
import useCategoryStore from '@/store/module/category'
//引入接口API
import {
  getAttrList,
  reqAddOrUpdateAttr,
  reqDeleteAttrById,
} from '@/api/product/attr/index'
//接口数据类型
import type { Attr, AttrValue } from '@/api/product/attr/type'
import { ref, watch, onMounted, reactive, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
let CategoryStore = useCategoryStore()
//储存请求来的数据的临时数组
let AttrList = ref<Attr[]>([])
//遮罩层
let loding = ref(false)
//控制添加与展示的隐藏于和消失
let isShow = ref(false)
//用来储存添加的临时数组
let attr = reactive<Attr>({
  //属性名
  attrName: '',
  attrValueList: [],
  // 所属于三级分类的id
  categoryId: '',
  // 所属于那一集分类
  categoryLevel: 3,
})
// 用于初始化对象
const cearn = {
  //属性名
  attrName: '',
  attrValueList: [],
  // 所属于三级分类的id
  categoryId: '',
  // 所属于那一集分类
  categoryLevel: 3,
}
// //统一编码储存input数据
// let inputArr = ref<any>([])
//DOM渲染完毕后向服务器请求数据
onMounted(() => {
  if (CategoryStore.c3Id) {
    getAttr()
  }
})
//请求列表数据方法
const getAttr = async () => {
  //把需要的数据从对象解构出来
  const { c1Id, c2Id, c3Id } = CategoryStore
  //让loding遮罩
  loding.value = true
  let result = await getAttrList(c1Id, c2Id, c3Id)
  if (result.code == 200) {
    AttrList.value = result.data
    // 成功让loding停止
    loding.value = false
  } else {
    // 失败让loding停止
    loding.value = false
    ElMessage({
      type: 'error',
      message: '请求超时',
    })
  }
}
//监听三级id是否有变化
watch(
  () => CategoryStore.c3Id,
  (value) => {
    //判断更新后的值是否为空
    if (value) {
      //不为空获取数据
      getAttr()
    }
  },
)
//添加属性名称并新建属性值
const addValueList = () => {
  //把三级分类id拿过来
  attr.categoryId = CategoryStore.c3Id
  //在数组新建一个对象用于储存和处理临时的值
  attr.attrValueList.push({ valueName: '', flag: true })
  //统一编码001添加一个el-input等待dom渲染完毕后给elinput加focus事件
  // nextTick(() => {
  //   inputArr.value[inputArr.value.length - 1].focus()
  // })
}
//提交上传数据
const saveAttrList = async () => {
  let result = await reqAddOrUpdateAttr(attr)
  if (result.code == 200) {
    //添加成功后显示列表隐藏添加卡片
    isShow.value = false
    ElMessage({
      type: 'success',
      message: attr.id ? '修改成功' : '添加成功',
    })
    // 添加成功重新请求数据更新列表数据
    getAttr()
    clearnAttr()
  } else {
    ElMessage({
      type: 'error',
      message: attr.id ? '修改失败' : '添加失败',
    })
  }
}
//点击取消清空数据
const clearnAttr = () => {
  Object.assign(attr, JSON.parse(JSON.stringify(cearn)))
}
//input失去焦点后
const mouseBlur = (row: AttrValue, index: number) => {
  //判断内容是否为空
  if (row.valueName != '') {
    //判断是否有与数组重复的值
    let res = attr.attrValueList.find((item) => {
      //当前row里面的自定义属性flag默认是true而已经失去焦点的item的值都是false,
      // 这样就可以把当前的最后一次的item过滤掉,因为无论如何当前item都等于row
      if (item != row) {
        //让当前的值和之前的item值对比，不让同一时期的item和row进来这样就能实现过滤查重
        return item.valueName === row.valueName
      }
    })
    //当res为true的时候说明是重复值
    if (res) {
      //将重复的数据清空
      attr.attrValueList.splice(index, 1)
      //警告用户不能输入重复的值
      ElMessage({
        type: 'error',
        message: '属性值不能重复!',
      })
    } else {
      //让input隐藏显示数据div
      row.flag = false
    }
  } else {
    //有重复值将空数据清空
    attr.attrValueList.splice(index, 1)
    ElMessage({
      type: 'warning',
      message: '非法数据!!!',
    })
  }
}
//点击div变成编辑模式
const editCon = (row: AttrValue) => {
  row.flag = true
  // , index?: number
  //统一编码001当修改时等待dom渲染完毕后给elinput加focus事件
  // nextTick(() => {
  //   inputArr.value[index].focus()
  // })
}
//自定义指令当dom元素在页面被渲染后自动聚焦
const vFocus = {
  mounted(el: HTMLElement) {
    el.querySelector('input')?.focus()
  },
}
//点击修改的时候
const updateAttrValue = (row: AttrValue) => {
  //深拷贝数据
  Object.assign(attr, JSON.parse(JSON.stringify(row)))
  isShow.value = true
}
//删除attr属性
const attrDelete = async (id: number) => {
  let result = await reqDeleteAttrById(id)
  if (result.code == 200) {
    ElMessage({ type: 'success', message: '删除成功' })
    getAttr()
  } else {
    ElMessage({ type: 'error', message: '删除失败' })
  }
}
onBeforeUnmount(() => {
  useCategoryStore().$reset()
})
</script>
<style scoped lang="scss"></style>
